<template>
  <div id="WallpaperCategory">
    <a-card class="container">
      <a-form
        :model="formSearchParams"
        :style="{ marginBottom: '20px' }"
        layout="inline"
        @submit="doSearch"
      >
        <a-form-item name="id" label="编号">
          <a-input
            v-model:value="formSearchParams.id"
            placeholder="请输入壁纸分类编号"
          />
        </a-form-item>
        <a-form-item name="userName" label="壁纸分类名">
          <a-input
            v-model:value="formSearchParams.name"
            placeholder="请输入壁纸分类名"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" style="width: 100px">
            搜索
          </a-button>
          <a-button
            @click="doReset"
            type="default"
            html-type="button"
            style="margin-left: 15px; width: 100px"
          >
            重置
          </a-button>
        </a-form-item>
      </a-form>
      <a-space style="margin: 0 0 15px">
        <a-button
          type="primary"
          :icon="h(PlusOutlined)"
          @click="showModal('add', {} as any)"
          >添加壁纸分类
        </a-button>
      </a-space>
      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="{
          current: searchParams.pageNo,
          pageSize: searchParams.pageSize,
          pageSizeOptions,
          total,
          showSizeChanger: true,
          showTotal: (total: number, range: number[]) =>
            `共 ${total} 条数据 第 ${range[0]}-${range[1]} 条`,
        }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-button
              type="link"
              size="small"
              @click="showModal('edit', record)"
              style="padding: 0"
              >修改
            </a-button>
            <a-button type="link" danger size="small" @click="doDelete(record)"
              >删除
            </a-button>
          </template>
          <template v-else-if="column.key === 'picUrl'">
            <template v-if="record.picUrl">
              <a-image
                :src="record.picUrl"
                alt="壁纸分类头像"
                :width="50"
                :height="50"
                style="object-fit: cover"
              />
            </template>
            <template v-else>
              <a-image
                :width="50"
                :height="50"
                :preview="false"
                src="https://www.antdv.com/#error"
                fallback=""
              />
            </template>
          </template>
          <template v-else-if="column.key === 'selected'">
            <a-switch
              v-model:checked="record.selected"
              :checked-value="1"
              :un-checked-value="0"
              size="small"
              @change="selectedChange(record)"
            />
          </template>
          <template v-else-if="column.key === 'enabled'">
            <a-switch
              v-model:checked="record.enabled"
              :checked-value="1"
              :un-checked-value="0"
              size="small"
              @change="enabled(record)"
            />
          </template>
        </template>
      </a-table>
    </a-card>
    <CategoryModal
      :model-value="open"
      :title="title"
      :on-cancel="onCancel"
      :on-ok="handleOk"
      :width="600"
      :record="currentRow"
    />
  </div>
</template>
<script lang="ts" setup>
import {
  ExclamationCircleOutlined,
  PlusOutlined,
  SmileOutlined,
} from "@ant-design/icons-vue";
import { message, Modal } from "ant-design-vue";
import { createVNode, h, ref, watchEffect } from "vue";
import Api from "../../../../api";
import {
  WallpaperCategoriesPageReqDTO,
  WallpaperCategoriesVo,
} from "../../../../api/globals";
import CategoryModal from "./CategoryModal.vue";

const pageSizeOptions = ref<string[]>(["10", "20", "30", "40", "50"]);

const open = ref<boolean>(false);
const title = ref<string>("添加");
const currentRow = ref<WallpaperCategoriesVo>({} as WallpaperCategoriesVo);

// 确认提交 可能是更新可能是创建
const handleOk = () => {
  open.value = false;
  currentRow.value = {} as WallpaperCategoriesVo;
  fetchData();
};

const showModal = (type: string, record: WallpaperCategoriesVo) => {
  open.value = true;
  title.value = type === "add" ? "添加壁纸分类" : "修改壁纸分类";
  currentRow.value = record;
};

const onCancel = () => {
  open.value = false;
  currentRow.value = {} as WallpaperCategoriesVo;
};

// 初始化搜索条件（不应该被修改）
const initSearchParams = {
  pageNo: 1,
  pageSize: 10,
};

const searchParams = ref({
  ...initSearchParams,
});

const formSearchParams = ref<WallpaperCategoriesPageReqDTO>(
  {} as WallpaperCategoriesPageReqDTO,
);
/**
 * 执行搜索
 */
const doSearch = () => {
  searchParams.value = {
    ...initSearchParams,
    ...formSearchParams.value,
  };
};

// 数据
const dataList = ref<WallpaperCategoriesVo[]>([]);
const total = ref(0);

// 获取数据
const fetchData = async () => {
  const res = await Api.general.getWallpaperCategoriesPage({
    params: {
      ...searchParams.value,
    } as any,
  });
  if (res.data) {
    dataList.value = res.data.list || [];
    total.value = res.data.total || 0;
  } else {
    message.error("获取数据失败 " + res.msg);
  }
};

// 分页变化函数
const handleTableChange = (pagination: any) => {
  searchParams.value = {
    ...searchParams.value,
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
  };
  fetchData();
};

watchEffect(() => {
  fetchData();
});

/**
 * 删除
 * @param record
 */
const doDelete = async (record: WallpaperCategoriesVo) => {
  if (!record.id) {
    return;
  }
  Modal.confirm({
    title: "确认要删除此壁纸分类吗?",
    icon: createVNode(ExclamationCircleOutlined),
    onOk: async () => {
      const res = await Api.general.deleteWallpaperCategories({
        params: {
          id: record.id as number,
        },
      });
      if (res.code === 0) {
        await fetchData();
        message.success("删除成功");
      } else {
        message.error("删除失败，" + res.msg);
      }
    },
  });
};

/**
 * 重置搜索条件
 */
const doReset = () => {
  searchParams.value = {
    ...initSearchParams,
  };
  formSearchParams.value = {} as WallpaperCategoriesPageReqDTO;
};

/**
 * 修改推荐分类状态
 */
const selectedChange = async (record: WallpaperCategoriesVo) => {
  const res = await Api.general.updateWallpaperCategoriesSelected({
    data: {
      id: record.id as number,
      status: record.selected as any,
    },
  });
  if (res.code === 0) {
    await fetchData();
    message.success("修改成功");
  } else {
    message.error("修改失败，" + res.msg);
  }
};

/**
 * 修改是否启用状态
 */
const enabled = async (record: WallpaperCategoriesVo) => {
  const res = await Api.general.updateWallpaperCategoriesEnabled({
    data: {
      id: record.id as number,
      status: record.enabled as any,
    },
  });
  if (res.code === 0) {
    await fetchData();
    message.success("修改成功");
  } else {
    message.error("修改失败，" + res.msg);
  }
};

const columns = [
  {
    key: "id",
    title: "id",
    dataIndex: "id",
    width: "80px",
  },
  {
    key: "name",
    title: "分类名称",
    dataIndex: "name",
  },
  {
    key: "sort",
    title: "排序",
    dataIndex: "sort",
  },
  {
    key: "picUrl",
    title: "缩略图",
    dataIndex: "picUrl",
  },
  {
    key: "selected",
    title: "推荐分类",
    dataIndex: "selected",
  },
  {
    key: "enabled",
    title: "状态",
    dataIndex: "enabled",
  },
  {
    title: "操作",
    key: "action",
  },
];
</script>
<style scoped></style>
